package com.guxingke.typecho4j.util;

import com.jfinal.core.Controller;

/**
 * 关于jfinal controller的一些工具方法
 * 
 * @author guxingke
 */
public class ControllerUtil {

	/**
	 * 获取RequestURI中的urlPara<br/>
	 * 获取最后一个“/”后的字符串
	 * 
	 * @param controller
	 * @return
	 */
	public static String getUrlPara(Controller controller) {
		String[] temps = getRequestURI(controller).split("/");
		return temps[temps.length - 1];
	}

	/**
	 * 获取URI
	 * 
	 * @param controller
	 * @return
	 */
	private static String getRequestURI(Controller controller) {
		return controller.getRequest().getRequestURI();
	}

	/**
	 * 获取执行key
	 * 
	 * @param controller
	 * @return
	 * 
	 * @deprecated 替换方法为 getDispatcherKey
	 */
	@Deprecated
	public static String getExcuteKey(Controller controller) {
		String[] temp = controller.getRequest().getRequestURI()
				.split("/");
		if (temp.length < 2) {
			return "/";
		}
		return "/" + temp[1];
	}

	/**
	 * 获取处理key
	 * 
	 * @param controller
	 * @return
	 * 
	 * @deprecated 替换方法为 getDispatcherKey
	 */
	@Deprecated
	public static String getHandleKey(Controller controller) {
		String handlerKey = controller.getPara("do");
		return handlerKey;
	}

	/**
	 * 获取分发key,即路由的responseKey
	 * 
	 * @param controller
	 * @return String
	 * 
	 */
	public static String getDispatcherKey(Controller controller) {
		String handlerKey = controller.getPara("do");
		if (handlerKey != null) {
			return handlerKey;
		}

		String requestURI = getRequestURI(controller);
		String[] temp = requestURI.split("/");

		if (!requestURI.startsWith("/admin")) {
			if (temp.length < 2) {
				return "/";
			}
			return "/" + temp[1];
		} else {
			if (temp.length < 3) {
				return "/" + temp[1];
			}
			return "/" + temp[1] + "/" + temp[2];
		}
	}
}
